<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="产品名称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-cascader
            v-model="queryParams.category_id"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'category_id', label: 'name' }"
            clearable
            placeholder="选择分类"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增产品</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-wrapper">
      <el-table v-loading="loading" :data="productList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="name" label="产品名称" min-width="200" show-overflow-tooltip />
        <el-table-column label="封面图" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.cover_image"
              :src="row.cover_image"
              :preview-src-list="[row.cover_image]"
              fit="cover"
              style="width: 60px; height: 60px"
            />
            <el-icon v-else><Picture /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="category.name" label="分类" min-width="120" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" min-width="100">
          <template #default="{ row }">
            {{ formatAmount(row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="market_price" label="市场价" min-width="100">
          <template #default="{ row }">
            {{ formatAmount(row.market_price) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" align="center" />
        <el-table-column prop="sales" label="销量" width="80" align="center" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button :type="row.status ? 'danger' : 'success'" link @click="handleStatus(row)">
              {{ row.status ? '下架' : '上架' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          small
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="category_id">
          <el-cascader
            v-model="form.category_id"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'category_id', label: 'name' }"
            placeholder="请选择分类"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="10" />
        </el-form-item>
        <el-form-item label="市场价" prop="market_price">
          <el-input-number v-model="form.market_price" :min="0" :precision="2" :step="10" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover_image">
          <el-upload
            class="avatar-uploader"
            action="/admin/upload"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.cover_image" :src="form.cover_image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片集" prop="images">
          <el-upload
            action="/admin/upload"
            list-type="picture-card"
            :file-list="imageList"
            :on-success="handleImageSuccess"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入产品简介" />
        </el-form-item>
        <el-form-item label="详细内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入详细内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  category_id: undefined,
  status: ''
})

// 数据列表
const loading = ref(false)
const productList = ref([])
const total = ref(0)
const categoryOptions = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  product_id: undefined,
  category_id: undefined,
  name: '',
  price: 0,
  market_price: 0,
  cover_image: '',
  images: [],
  description: '',
  content: '',
  stock: 0,
  sort: 0
})

// 图片列表
const imageList = ref([])

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  category_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  market_price: [{ required: true, message: '请输入市场价', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await request.get('/product-category/list')
    categoryOptions.value = res.data.list
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取产品列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/product/list', { params: queryParams })
    productList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取产品列表失败:', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.category_id = undefined
  queryParams.status = ''
  handleSearch()
}

// 新增产品
const handleAdd = () => {
  dialogTitle.value = '新增产品'
  form.product_id = undefined
  form.category_id = undefined
  form.name = ''
  form.price = 0
  form.market_price = 0
  form.cover_image = ''
  form.images = []
  form.description = ''
  form.content = ''
  form.stock = 0
  form.sort = 0
  imageList.value = []
  dialogVisible.value = true
}

// 编辑产品
const handleEdit = (row) => {
  dialogTitle.value = '编辑产品'
  Object.assign(form, row)
  imageList.value = (row.images || []).map(url => ({ url }))
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return

    try {
      const url = form.product_id ? '/product/update' : '/product/create'
      await request.post(url, form)
      ElMessage.success(form.product_id ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
    }
  })
}

// 删除产品
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该产品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/product/delete', { product_id: row.product_id })
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 更新状态
const handleStatus = async (row) => {
  try {
    await request.post('/product/status', {
      product_id: row.product_id,
      status: row.status ? 0 : 1
    })
    ElMessage.success('状态更新成功')
    getList()
  } catch (error) {
    console.error('状态更新失败:', error)
  }
}

// 上传相关
const handleCoverSuccess = (res) => {
  form.cover_image = res.data.url
}

const handleImageSuccess = (res) => {
  form.images.push(res.data.url)
}

const handleImageRemove = (file) => {
  const index = form.images.indexOf(file.url)
  if (index !== -1) {
    form.images.splice(index, 1)
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 分页相关
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount).toFixed(2)
}

onMounted(() => {
  getCategoryList()
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-wrapper {
    margin-bottom: 20px;
  }

  .table-wrapper {
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
</style> 